//
//  BrowsingHistoryViewController.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/10/12.
//

import UIKit
import MJRefresh

class BrowsingHistoryViewController: BaseViewController {
    var clearBtn: UIButton!
    var emptyView: LYEmptyView!
    var collectionView: UICollectionView!
    var pageNumber = 1
    var dataArray = NSMutableArray()
    var goTopBtn: UIButton = {
        let tempBtn = UIButton()
        tempBtn.setup_image(image: UIImage.init(named: "icon_suspend"))
        tempBtn.isHidden = true
        return tempBtn
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.title = MMLocalizedString("browsing_history", comment: "浏览记录")
        self.navBar.wr_setBottomLineHidden(hidden: true)
        self.initNav()
        self.initCollectionView()
        self.requestGoodsBrowse(isMore: false)
        
        self.view.addSubview(goTopBtn)
        self.addSnpLayout()
    }
    
    private func addSnpLayout(){
        self.goTopBtn.snp.makeConstraints { make in
            make.left.equalTo(12)
            make.bottom.equalTo(-TabbarHeight)
            make.width.equalTo(44)
            make.height.equalTo(44)
        }
    }
  
    func initNav(){
        clearBtn = UIButton(frame: .zero)
        clearBtn.setTitle(MMLocalizedString("clear", comment: "清空"), for: .normal)
        clearBtn.titleLabel?.font = UIFont(name: Theme.PingFangSCMedium, size: 14)
        clearBtn.setTitleColor(Theme.mainColor, for: .normal)
        clearBtn.addTarget(self, action: #selector(clearBtnAntion), for: .touchUpInside)
        self.navBar.addSubview(clearBtn)
        clearBtn.snp.makeConstraints { make in
            make.right.equalTo(-14)
            make.width.height.equalTo(44)
            make.bottom.equalTo(0)
        }
    }
    
    
    func initCollectionView(){
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = 10
        layout.minimumLineSpacing = 10
        layout.scrollDirection = .vertical
        let ww = (kScreenWidth - 38)/2
        layout.itemSize = CGSize(width: ww, height: 210)
        layout.sectionInset = UIEdgeInsets(top: 7, left: 14, bottom: 0, right: 14)
        self.collectionView = UICollectionView(frame: CGRect(x: 0, y: NavBarHight, width: kScreenWidth, height: kScreenHeight - NavBarHight), collectionViewLayout: layout)
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.register(GoodsCollectionViewCell.self, forCellWithReuseIdentifier: "GoodsCollectionViewCell")
        self.collectionView.backgroundColor = .white
        self.view.addSubview(self.collectionView)
        self.collectionView.showsVerticalScrollIndicator = false
        
        self.setUpNoData()
        self.addPullRefreash()
        self.addLoadMoreRefreash()
        
    }
    
    ///空视图
    func setUpNoData() {
        self.emptyView = LYEmptyView.emptyActionView(withImageStr: "icon_empty", titleStr: MMLocalizedString("save_the_browsing_history", comment: "登录可保存最近30天浏览记录"), detailStr: "", btnTitleStr: "") {
        }
        emptyView.titleStr = ""
        emptyView?.subViewMargin = 28
        emptyView?.contentViewOffset = -50
        emptyView.isHidden = true
        self.collectionView.ly_emptyView = self.emptyView
    }

    
    ///空视图
    func willShowEmptyView() {
        if self.dataArray.count == 0 {
            self.clearBtn.isHidden = true
            self.collectionView.mj_footer?.isHidden = true
            self.emptyView.isHidden = false
            self.emptyView?.titleStr = MMLocalizedString("save_the_browsing_history", comment: "登录可保存最近30天浏览记录")
        }else{
            self.clearBtn.isHidden = false
            self.emptyView.isHidden = true
            self.emptyView?.titleStr = ""
        }
    }
    
    /*
     * 添加头部刷新
     */
    func addPullRefreash()  {
        weak var weakself = self
        self.collectionView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            weakself?.pageNumber = 1
            weakself?.requestGoodsBrowse(isMore: false)
        })
    }
    
    
    //MARK: -  底部刷新
    func addLoadMoreRefreash()  {
        weak var weakself = self
        self.collectionView.mj_footer = ExtNoMoreRefreashFooterView.init(refreshingBlock: {
            weakself?.pageNumber = weakself!.pageNumber + 1
            weakself?.requestGoodsBrowse(isMore: true)
        })
    }
    
    //MARK: - Request
    //获取浏览记录列表
    func requestGoodsBrowse(isMore: Bool){
        if isMore{
            self.view.showLoadingHUDText(nil)
        }
        let param = ["pageNumber": "\(self.pageNumber)","pageSize": "10"]
        
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.getGoodsBrowse(param: param), objectType: BrowsingHistoryModel.self) { data in
            self.collectionView.mj_footer?.endRefreshing()
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.isHidden = false
            self.view.handleLoading()
            let resultObj = data as! BrowsingHistoryModel
            if resultObj.code == "1"{
                if isMore == false {
                    self.dataArray.removeAllObjects()
                }
                let dataContent = resultObj.data?.content ?? []
                if dataContent.count < 10 {
                    self.collectionView.mj_footer?.endRefreshingWithNoMoreData()
                }
                self.dataArray.addObjects(from: dataContent)
                
                //是否收藏
                self.dataArray.map{$0 as? VehicleLisetModel}.forEach({ item in
                    item?.favoriteBlock = { [weak self] in
                        self?.requestFavorite(model: item!)
                    }
                })
            }
       
            self.collectionView.reloadData()
            self.willShowEmptyView()
        } error: { err in
            self.willShowEmptyView()
            self.view.handleLoading()
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
            self.view.makeToast(message: err?.domain ?? MMLocalizedString("request_failed", comment: "请求失败，请稍候再试"))
        }
    }
    
    //收藏取消收藏
    func requestFavorite(model: VehicleLisetModel){
        if UserModule.shared.isLogined == false{
            self.jumpToLogin()
            return
        }
        let param = ["usedcarId": "\(model.id ?? 0)"]
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.favorite(param: param),objectType: CommondResModel.self) { data in
            let resultObj = data as! CommondResModel
            if resultObj.code == "1" {
                if model.favorite == false{
                    self.view.makeToast(message: MMLocalizedString("successful_collection", comment: "收藏成功"))
                }else{
                    self.view.makeToast(message: MMLocalizedString("uncollected", comment: "已取消收藏"))
                }
                //延迟
                DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                    self.requestGoodsBrowse(isMore: false)
                }
            }else{
                self.view.makeToast(message: resultObj.msg ?? "")
            }
        }error: { err in
            
        }
    }
    
    
    //清空浏览记录
    func requestClearGoodsBrowse(){
        self.view.showLoadingHUDText(nil)
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.clearBrowsingHistory, objectType: CommondResModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as! CommondResModel
            if resultObj.code == "1" {
                self.view.makeToast(message: MMLocalizedString("successfully_delete", comment: "删除成功"))
                self.requestGoodsBrowse(isMore: false)
            }
        } error: { err in
            self.view.handleLoading()
            self.view.makeToast(message: err?.domain ?? MMLocalizedString("request_failed", comment: "请求失败，请稍候再试"))
        }

    }
    
    //MARK: - Antion
    @objc func clearBtnAntion(){
        XTAlertView.showAlertView(title: MMLocalizedString("hint", comment: "提示"),
                                  message: MMLocalizedString("clear_browsing_history", comment: "确定清空浏览记录吗?"),
                                  cancelButtonTitle: MMLocalizedString("cancel", comment: "取消"),
                                  otherButtonTitlesArr: [MMLocalizedString("confirm", comment: "确定")]) { alert, tag in
            if tag == 1 {
                //确定
                self.requestClearGoodsBrowse()
            }
        }
    }
    
    //MARK: - Antion
    @objc func jumpToLogin(){
        guard let tabbarVC = UIApplication.shared.keyWindow?.rootViewController as? BaseTabbarController else {
            return
        }
        let vc = LoginViewController()
        let loginNavi = BaseNavigationController.init(rootViewController: vc)
        loginNavi.modalPresentationStyle = .fullScreen
        tabbarVC.present(loginNavi, animated: true)
    }
    
}

extension BrowsingHistoryViewController: UICollectionViewDataSource,UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GoodsCollectionViewCell", for: indexPath) as! GoodsCollectionViewCell
        if self.dataArray.count > indexPath.row{
            let model = self.dataArray[indexPath.row] as! VehicleLisetModel
            cell.setModel(model: model)
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if self.dataArray.count > indexPath.row{
            let model = self.dataArray[indexPath.row] as! VehicleLisetModel
            let vc = VehicleDetailsViewController()
            vc.id = "\(model.id ?? 0)"
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
}

extension BrowsingHistoryViewController: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offset = scrollView.contentOffset.y
        if offset <= kScreenHeight/2 {
            self.goTopBtn.isHidden = true
        }else{
            self.goTopBtn.isHidden = false
        }
    }
}
